#!/usr/bin/env node

const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

// 云函数部署脚本
function deployCloudFunctions() {
  const cloudFunctionsDir = path.join(__dirname, 'cloudfunctions')
  
  if (!fs.existsSync(cloudFunctionsDir)) {
    console.error('cloudfunctions 目录不存在')
    return
  }

  const functions = fs.readdirSync(cloudFunctionsDir)
    .filter(item => fs.statSync(path.join(cloudFunctionsDir, item)).isDirectory())

  console.log('开始部署云函数...')
  console.log('找到的云函数:', functions)

  functions.forEach(funcName => {
    const funcPath = path.join(cloudFunctionsDir, funcName)
    console.log(`\n部署云函数: ${funcName}`)
    
    try {
      // 安装依赖
      console.log('安装依赖...')
      execSync('npm install', { 
        cwd: funcPath, 
        stdio: 'inherit' 
      })
      
      // 部署云函数
      console.log('部署云函数...')
      execSync(`tcb fn deploy ${funcName}`, { 
        cwd: cloudFunctionsDir, 
        stdio: 'inherit' 
      })
      
      console.log(`✅ ${funcName} 部署成功`)
    } catch (error) {
      console.error(`❌ ${funcName} 部署失败:`, error.message)
    }
  })
}

// 运行部署
if (require.main === module) {
  deployCloudFunctions()
}

module.exports = { deployCloudFunctions } 